package com.ctg.itrdc.imageconsole.common.util;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;

  
 
public class ZooKeeperOperator extends AbstractZooKeeper {  
	private static Logger logger = Logger.getLogger(ZooKeeperOperator.class);
	
	public ZooKeeperOperator() {
		
	}
	
    /**
     * 创建父节点
     * @param path
     * @throws KeeperException
     * @throws InterruptedException
     */
    public void createParentNode(String path)throws KeeperException, InterruptedException{  
        this.zooKeeper.create(path, "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);  
    } 
    
    /**
     * 创建叶子节点
     * @param path
     * @param data
     * @throws KeeperException
     * @throws InterruptedException
     */
    public void createChildNode(String path,byte[] data)throws KeeperException, InterruptedException{  
    	this.zooKeeper.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);  
    }  
    /** 
     *判断节点是否存在
     *@author yezhineng
     *@param path 
     *@throws KeeperException 
     *@throws InterruptedException 
     */  
    public boolean getChild(String path) throws KeeperException, InterruptedException{    
        try{  
            this.zooKeeper.getChildren(path, false);  
            return true; 
        }catch (KeeperException.NoNodeException e) {  
             return false;
        } 
    }  
      
    public byte[] getData(String path) throws KeeperException, InterruptedException {     
        return  this.zooKeeper.getData(path, false,null);     
    }  
    
    public void update(String path,byte[] data){
    	try {
			this.zooKeeper.setData(path, data, -1);
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    }
    
    public void delete(String path){
    	try {
    		logger.info("delete node:" + path);
			this.zooKeeper.delete(path, -1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (KeeperException e) {
			e.printStackTrace();
		}
    }
    
    public void startTomcat(String command){
    	Process process;
        try {  
        	process = Runtime.getRuntime().exec(command);  
        	InputStreamReader ir = new InputStreamReader(process.getInputStream());  
            LineNumberReader input = new LineNumberReader(ir);  
            String line;  
            process.waitFor();  
            while ((line = input.readLine()) != null){  
                logger.info(line);
            }
        } catch (IOException | InterruptedException e) {  
            e.printStackTrace();  
        }  
    }
    
    public List<String> getNode(String path) throws KeeperException, InterruptedException{
    	return this.zooKeeper.getChildren(path, false);
    }
}  